package com.sd.view;

import java.io.File;
import java.net.URLDecoder;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.alex.http.AGetReuqest;
import com.alex.http.AHandledResult;
import com.alex.http.AHttpEngine;
import com.alex.http.AHttpListener;
import com.alex.log.ALog;
import com.sd.activity.AlixDemo;
import com.sd.activity.CHLCardRechargeActivity;
import com.sd.activity.CHLMessageRechargeActivity;
import com.sd.activity.CHUCardRechargeActivity;
import com.sd.activity.CHUMessageRechargeActivity;
import com.sd.activity.CTMessageRechargeActivity;
import com.sd.activity.GuideActivity;
import com.sd.activity.MainTabActivity;
import com.sd.activity.SubmitActivity;
import com.sd.activity.r.R;
import com.sd.app.AppData;
import com.sd.util.DownloaderApk;
import com.sd.util.LoadingProgressDialog;
import com.sd.util.QequestHandleable;
import com.snda.woa.android.OpenAPI;
import com.snda.woa.android.callback.FastLoginCallBack;
import com.snda.woa.android.callback.PwdLoginCallBack;

/**
 * 
 * 
 * @author Alex.Lu
 * 
 */
public class DialogManager implements OnClickListener {

	private long REQUEST_VERSION = 0x01;
	private long REQUEST_DOWN = 0x02;
	
	private static DialogManager instance;
	private Dialog mDialog;
	private Context mContext;

	public static DialogManager getInstance() {
		if (instance == null) {
			instance = new DialogManager();
		}
		return instance;
	}

	/**
	 * 是否退出客户端的对话框
	 */
	public void createExitDialog(final Context context) {
		Builder builder = new AlertDialog.Builder(context);
		
		builder.setMessage(context.getString(R.string.msg_exit)).setPositiveButton(
				R.string.btn_ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						System.exit(0);
					}
				}).setNegativeButton(R.string.btn_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				}).show();
	}
	
	/**
	 * 是否退出客户端的对话框
	 */
	public void createUpdateDialog(final Context context,final String url,final AHttpListener listener) {
		Builder builder = new AlertDialog.Builder(context);
		
		builder.setMessage(context.getString(R.string.msg_has_new_verison)).setPositiveButton(
				R.string.btn_once_update, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						LoadingProgressDialog.show(context, R.string.msg_loading);
						AGetReuqest get = new AGetReuqest(REQUEST_DOWN, url, listener);
			            get.setHandleable(new DownloaderApk());
			            AHttpEngine.getInstance().request(get);
					}
				}).setNegativeButton(R.string.btn_once_no,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				}).show();
	}
	
	
	
	public void createSystemSet(final Context context, OnClickListener listener) {
		mContext = context;
		mDialog = new Dialog(context, R.style.dialog);
		LayoutInflater mInflater = LayoutInflater.from(context);
		View view = mInflater.inflate(R.layout.dialog_system_set, null);
		// mPopWindow = new PopupWindow(view);
		/**
		 * 快速入门
		 */
		ImageButton guideBT = (ImageButton) view.findViewById(R.id.guide_bt);
		guideBT.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(context, GuideActivity.class);
				context.startActivity(intent);
				mDialog.dismiss();
			}
		});
		
		/**
		 * 软件更新
		 */
		ImageButton updateBT = (ImageButton) view.findViewById(R.id.update_bt);
		updateBT.setOnClickListener(new OnClickListener() {

			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//发送更新请求
				/*Intent intent= new Intent();        
                intent.setAction("android.intent.action.VIEW");    
                Uri content_url = Uri.parse("http://221.181.69.73/turntest.apk");   
                intent.setData(content_url);           
                intent.setClassName("com.android.browser","com.android.browser.BrowserActivity");   
                context.startActivity(intent);*/
				LoadingProgressDialog.show(mContext, R.string.msg_loading);
				String url = "http://version.4gshu.com/version?type="+AppData.getInstance().mClient+"&oldver="+AppData.getInstance().mClientVerison;
                AGetReuqest get = new AGetReuqest(REQUEST_VERSION, url, httpListener);
                get.setHandleable(new QequestHandleable());
                AHttpEngine.getInstance().request(get);
				
				/*LoadingProgressDialog.show(mContext, R.string.msg_loading);
				AGetReuqest get = new AGetReuqest(REQUEST_DOWN, "http://221.181.69.73/jp_reader.apk", httpListener);
	            get.setHandleable(new DownloaderApk());
	            AHttpEngine.getInstance().request(get);*/
                
                mDialog.dismiss();
			}
		});
		/**
		 * 提交建议
		 */
		ImageButton submitBT = (ImageButton) view.findViewById(R.id.submit_bt);
		submitBT.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mDialog.dismiss();
				Intent intent = new Intent();
				intent.setClass(context, SubmitActivity.class);
				context.startActivity(intent);
			}
		});

		/**
		 * 退出程序
		 */
		ImageButton exitBT = (ImageButton) view.findViewById(R.id.exit_bt);
		exitBT.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				System.exit(0);
			}
		});
		mDialog.setContentView(view);
		mDialog.setCanceledOnTouchOutside(true);
		mDialog.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode,
                    KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_MENU&& event.getAction() == KeyEvent.ACTION_DOWN)// 监听按键
                	mDialog.dismiss();
                return false;
            }
        });
		mDialog.show();
	}

	public void createReaderSet(final Context context,
			OnClickListener listener, int bookId) {

		mDialog = new Dialog(context, R.style.dialog);
		LayoutInflater mInflater = LayoutInflater.from(context);
		View view = mInflater.inflate(R.layout.dialog_reader_set, null);

		ImageButton bookDelete = (ImageButton) view
				.findViewById(R.id.book_delete_bt);
		bookDelete.setOnClickListener(listener);
		bookDelete.setTag(bookId);

		ImageButton clean = (ImageButton) view.findViewById(R.id.clean_bt);
		clean.setOnClickListener(listener);
		ImageButton addBook = (ImageButton) view.findViewById(R.id.add_book_bt);
		addBook.setOnClickListener(listener);
		ImageButton readSet = (ImageButton) view.findViewById(R.id.read_set_bt);
		readSet.setOnClickListener(listener);
		ImageButton contiuneRead = (ImageButton) view
				.findViewById(R.id.contiune_read_bt);
		contiuneRead.setOnClickListener(listener);
		contiuneRead.setTag(bookId);
		ImageButton bookMark = (ImageButton) view
				.findViewById(R.id.bookmark_bt);
		bookMark.setOnClickListener(listener);
		bookMark.setTag(bookId);
		ImageButton bookInfo = (ImageButton) view
				.findViewById(R.id.bookinfo_bt);
		bookInfo.setTag(bookId);
		bookInfo.setOnClickListener(listener);
		ImageButton bookCatalogue = (ImageButton) view
				.findViewById(R.id.book_catalogue_bt);
		bookCatalogue.setOnClickListener(listener);
		bookCatalogue.setTag(bookId);
		mDialog.setContentView(view);
		mDialog.setCanceledOnTouchOutside(true);
		mDialog.show();
	}

	/**
	 * 
	 * @param context
	 * @param listener
	 * @param mobile
	 */
	public void createLogin(final Context context,
			final PwdLoginCallBack listener, final FastLoginCallBack mobile) {
		mDialog = new Dialog(context, R.style.dialog);
		LayoutInflater mInflater = LayoutInflater.from(context);
		View view = mInflater.inflate(R.layout.dialog_login, null);
		view.setLayoutParams(new LayoutParams(440, 440));
		Button mobileLogin = (Button) view.findViewById(R.id.mobilelogin);
		mobileLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				OpenAPI.fastLogin(mobile, true, 3, true, true, context, null);
				mDialog.dismiss();
			}
		});
		
		TextView mobileLoginHit = (TextView)view.findViewById(R.id.mobileloginhit);
		String str = context.getResources().getString(R.string.hint_fast_login);
		SpannableStringBuilder style=new SpannableStringBuilder(str); 
		int start1 = str.indexOf("（");
		style.setSpan(new ForegroundColorSpan(Color.RED), start1, start1+4, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		mobileLoginHit.setText(style);
		
		final EditText ptET = (EditText) view.findViewById(R.id.pt);
		final EditText pwdET = (EditText) view.findViewById(R.id.pwd);
		Button login = (Button) view.findViewById(R.id.login);
		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String pt = ptET.getText().toString();
				if(pt.equals("")){
					ToastManager.getInstance().showText(context, R.string.msg_error_input_uername);
					return ;
				}
				String pwd = pwdET.getText().toString();
				if(pwd.equals("")){
					ToastManager.getInstance().showText(context, R.string.msg_error_input_password);
					return ;
				}
				OpenAPI
						.pwdLogin(listener, pt, pwd, false, false, context,
								null);
				mDialog.dismiss();
				LoadingProgressDialog.show(context, R.string.msg_loading);
			}
		});

		Button cancel = (Button) view.findViewById(R.id.cancel);
		cancel.setOnClickListener(this);
		mDialog.setContentView(view);
		mDialog.setCanceledOnTouchOutside(true);
		mDialog.show();
	}

	public void createRechange(final Context context, OnClickListener listener) {
		mDialog = new Dialog(context, R.style.dialog);
		LayoutInflater mInflater = LayoutInflater.from(context);
		View view = mInflater.inflate(R.layout.dialog_rechange, null);
		Button alipay = (Button) view.findViewById(R.id.alipay);
		alipay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(context, AlixDemo.class);
				context.startActivity(intent);
				mDialog.dismiss();
			}
		});

		Button chlpay = (Button) view.findViewById(R.id.chlpay);
		chlpay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(context, CHLCardRechargeActivity.class);
				context.startActivity(intent);
				mDialog.dismiss();
			}
		});

		Button chupay = (Button) view.findViewById(R.id.chupay);
		chupay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(context, CHUCardRechargeActivity.class);
				context.startActivity(intent);
				mDialog.dismiss();
			}
		});
		Button chlmsg1pay = (Button) view.findViewById(R.id.chlmsg1);
		chlmsg1pay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(context, CHLMessageRechargeActivity.class);
				context.startActivity(intent);
				mDialog.dismiss();
			}
		});
		
		Button chlmsg2pay = (Button) view.findViewById(R.id.chlmsg2);
		chlmsg2pay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(context, CHUMessageRechargeActivity.class);
				context.startActivity(intent);
				mDialog.dismiss();
			}
		});
		
		Button chlmsg3pay = (Button) view.findViewById(R.id.chlmsg3);
		chlmsg3pay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(context, CTMessageRechargeActivity.class);
				context.startActivity(intent);
				mDialog.dismiss();
			}
		});
		mDialog.setContentView(view);
		mDialog.setCanceledOnTouchOutside(true);
		mDialog.show();
	}

	public void createPointChapter(final Context context,
			OnClickListener listener) {
		mDialog = new Dialog(context, R.style.dialog);
		LayoutInflater mInflater = LayoutInflater.from(context);
		View view = mInflater.inflate(R.layout.dialog_pointchapter, null);
		Button juan = (Button) view.findViewById(R.id.pick_up_juan);
		juan.setOnClickListener(listener);
		juan.setTag("卷");
		Button zhang = (Button) view.findViewById(R.id.pick_up_zhang);
		zhang.setOnClickListener(listener);
		zhang.setTag("章");
		Button hui = (Button) view.findViewById(R.id.pick_up_hui);
		hui.setOnClickListener(listener);
		hui.setTag("回");
		Button ji = (Button) view.findViewById(R.id.pick_up_ji);
		ji.setOnClickListener(listener);
		ji.setTag("集");
		Button jie = (Button) view.findViewById(R.id.pick_up_jie);
		jie.setOnClickListener(listener);
		jie.setTag("节");
		mDialog.setContentView(view);
		mDialog.setCanceledOnTouchOutside(true);
		mDialog.show();
	}
	
	public void createOrder(final Context context,
			DialogInterface.OnClickListener listener) {
		Builder builder = new AlertDialog.Builder(context);
		
		builder.setMessage(context.getString(R.string.msg_order_1)).setPositiveButton(
				R.string.btn_ok,listener).setNegativeButton(R.string.btn_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				}).show();
	}
	
	public void createOnline(final Context context,
			DialogInterface.OnClickListener listener) {
		Builder builder = new AlertDialog.Builder(context);
		
		builder.setMessage(context.getString(R.string.msg_order_2)).setPositiveButton(
				R.string.btn_ok,listener).setNegativeButton(R.string.btn_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				}).show();
	}

	public void dismiss() {
		if(mDialog!=null){
			mDialog.dismiss();
		}
	}
	
	public boolean isShow(){
		if(mDialog!=null && mDialog.isShowing()){
			return true;
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		mDialog.dismiss();
	}
	
	AHttpListener httpListener =new AHttpListener() {
		
		@Override
		public void onResult(long requestId, Bundle paramBundle,
				AHandledResult paramHandledResult) {
			// TODO Auto-generated method stub
			LoadingProgressDialog.dismiss();
			if(requestId == REQUEST_VERSION){
				Log.e("REQUEST_VERSION", "");
				ArrayList<String> list = (ArrayList<String>) paramHandledResult.mResults;
				String code = list.get(0);
				String url = list.get(1);
				if(code!=null && url != null && code.equals("1")){
					Log.e("REQUEST_VERSION", ""+url);
					url = URLDecoder.decode(url);
					/*LoadingProgressDialog.show(mContext, R.string.msg_loading);
					AGetReuqest get = new AGetReuqest(REQUEST_DOWN, url, httpListener);
		            get.setHandleable(new DownloaderApk());
		            AHttpEngine.getInstance().request(get);*/
					DialogManager.getInstance().createUpdateDialog(mContext,url,this);
				}else{
					ToastManager.getInstance().showText(mContext, "你已经是最新的版本了~~~");
				}
	            
			}else if(requestId == REQUEST_DOWN){
				LoadingProgressDialog.dismiss();
				Log.e("REQUEST_DOWN", "");
				Intent intent = new Intent(Intent.ACTION_VIEW);
				String apkName = (String)paramHandledResult.mObj;
				if(apkName!=null){
					File file = new File(apkName);
					intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
					mContext.startActivity(intent);
				}else{
					ToastManager.getInstance().showText(mContext, "你已经是最新的版本了~~~");
				}
			}
		}
		
		@Override
		public void onError(long requestId, Bundle paramBundle) {
			// TODO Auto-generated method stub
			ALog.e("onError");
			LoadingProgressDialog.dismiss();
			if(requestId == REQUEST_VERSION){
				ToastManager.getInstance().showText(mContext, "你已经是最新的版本了~~~");
			}else if(requestId == REQUEST_DOWN){
				ToastManager.getInstance().showText(mContext, "你已经是最新的版本了~~~");
			}
		}
	};

}
